package com.ruoyi.fjtseac.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.fjtseac.domain.dto.TypeDto;
import com.ruoyi.fjtseac.domain.vo.TypeVo;
import com.ruoyi.fjtseac.mapper.TypeMapper;
import com.ruoyi.fjtseac.domain.po.Type;
import com.ruoyi.fjtseac.service.TypeService;
import com.ruoyi.fjtseac.util.DtoToPoMapper;
import com.ruoyi.fjtseac.util.PoToVoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jxl
 * @since 2022-07-06
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {

    private TypeMapper typeMapper;

    @Autowired
    public TypeServiceImpl(TypeMapper typeMapper) {
        this.typeMapper = typeMapper;
    }

    @Override
    public AjaxResult addType(TypeDto typeDto) {
        Type type = DtoToPoMapper.INSTANCE.toType(typeDto);
        if(typeMapper.insert(type) >= 1) {
            return AjaxResult.success("添加类别成功");
        }
        return AjaxResult.error("添加失败");
    }

    @Override
    public AjaxResult deleteType(Integer typeId) {
        if(typeMapper.deleteById(typeId) >= 1) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @Override
    public AjaxResult updateType(TypeDto typeDto) {
        Type type = DtoToPoMapper.INSTANCE.toType(typeDto);
        if(typeMapper.updateById(type) >= 1) {
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public AjaxResult selectAllType() {
        List<Type> types = new ArrayList<>();
        types = typeMapper.selectList(null);
        if(types.size() == 0) {
            return AjaxResult.error("查询失败");
        }
        List<TypeVo> typeVos = new ArrayList<>();
        for (Type type : types) {
            TypeVo typeVo = PoToVoMapper.INSTANCE.toTypeVo(type);
            typeVos.add(typeVo);
        }
        return AjaxResult.success("查询成功", typeVos);
    }

}
